import TauPage from '@/components/TauPage';
import TauActionPanel from '@/components/TauActionPanel';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Checkbox } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import ChannelForm from './components/ChannelForm';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';

function Channel() {
  const [modal, setModal] = useState([]);
  const { channelStore: store } = useStore();
  const objRef = useRef(); // 当前选中的对象
  const [showOrders, setShowOrders] = useState(false);
  const [counts, setCounts] = useState([]);

  useEffect(() => {
    (async () => {
      await store.getCompany({ search: { status: 1 }, pg: { size: 999 } });
      await store.getDicts('channelType');
    })();
  }, []);

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const res = await fetchOrderCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showOrders, store.data]);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { channelDate, getOnDate, ...searchArgs } = params.values;
    const [from, to] = channelDate || [];
    const [fromTime, toTime] = getOnDate || [];
    store.search = {
      from,
      to,
      fromTime,
      toTime,
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    objRef.current = {};
    setModal(['add']);
  };

  // 点击打开查看
  const handleOpenView = (current) => {
    objRef.current = current;
    setModal(['view']);
  };

  // 点击打开编辑
  const handleOpenEdit = (current) => {
    objRef.current = current;
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create({ ...toJS(result), attachments: result?.attachments || [] });
        Message.success({ content: t`渠道创建成功` });
      } catch (e) {
        Message.error({ content: t`渠道创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 点击跳转到详情
  const handleToChannel = (record) => {
    global.Cookie.set('token', global.TOKEN, { path: '/', maxAge: 60 * 60 * 12 * 24 }); // 演示保存token到cookie, 有效期1分钟
    window.open(
      `${global.getEnvCfg().channelUrl}/?id=${record.id}`,
      'channel',
    );
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeChannel',
            title: t`添加渠道`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        searchItems={[
          {
            name: 'type',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.channelType),
              placeholder: t`渠道类型`,
            },
          },
          {
            name: 'state',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.state),
              placeholder: t`启用状态`,
            },
          },
          {
            name: 'upDate',
            type: 'date-range',
            props: {
              placeholder: [t`起始更新时间`, t`结束更新时间`],
            },
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', { width: 82, cell: (v, _, channel) => <Button type="primary" text onClick={() => handleOpenView(channel)}>{v}</Button> }),
            column('name', {}),
            column('typeText', {}),
            column('state', { width: 88 }),
            column('upDate', { width: 124, sortable: true }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 180,
              cell: (_, __, channel) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(channel)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" onClick={() => handleToChannel(channel)} >{t`详情`}</Button>
                </>),
            },
          ].filter((c) => c.dataIndex !== 'ccOrderCount' || showOrders)}
        />
      </div>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit' || modal[0] === 'view'}
        title={modal[0] === 'add' ? t`添加渠道` : t`修改渠道【${objRef.current?.name}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <ChannelForm
          channelId={objRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>

    </TauPage>
  );
}

export default observer(Channel);
